package concurrent.juc.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 黄嘉振
 * @create: 2023/6/15 16:05
 * @description:
 **/
public class TryLockDemo {
    public static void main(String[] args) {
        Task task = new Task();
        new Thread(task).start();
        new Thread(task).start();
    }
}

    class Task implements Runnable {
        static ReentrantLock lock = new ReentrantLock();

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            try {
                if (lock.tryLock(1, TimeUnit.SECONDS)) {
                // 获取不到锁会立刻返回false
//                if (lock.tryLock()) {
                    System.out.println(System.currentTimeMillis() + " " + name + " lock !");
                    Thread.sleep(3000);
                } else {
                    System.out.println(System.currentTimeMillis() + " " + name + " lock fail !!!");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    System.out.println(Thread.currentThread().getName() + "解锁成功！");
                    lock.unlock();
                }
            }
        }
    }
